<template>
  <div class="scores-container">
    <el-card class="scores-card">
      <template #header>
        <div class="card-header">
          <h3>体测成绩管理</h3>
          <div class="header-actions">
            <el-input v-model="searchText" placeholder="搜索学生姓名/学号" prefix-icon="el-icon-search" clearable @clear="handleSearch" style="width: 220px; margin-right: 10px" />
            <el-select v-model="itemFilter" placeholder="选择体测项目" clearable style="width: 160px; margin-right: 10px" @change="handleSearch">
              <el-option v-for="item in sportItems" :key="item.id" :label="item.itemName" :value="item.id" />
            </el-select>
            <el-button type="primary" @click="handleAdd">添加成绩</el-button>
          </div>
        </div>
      </template>

      <!-- 成绩列表 -->
      <el-table :data="paginatedScores" style="width: 100%" border v-loading="loading" :default-sort="{ prop: 'student.stuId', order: 'ascending' }">
        <el-table-column prop="student.stuId" label="学号" width="120" align="center" sortable />
        <el-table-column prop="student.name" label="姓名" width="100" align="center" />
        <el-table-column prop="student.gender" label="性别" width="60" align="center">
          <template #default="{ row }">
            <el-tag :type="row.student?.gender === '男' ? 'primary' : 'danger'" effect="plain" size="small">
              {{ row.student?.gender }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sportItem.itemName" label="项目名称" min-width="150" align="center" />
        <el-table-column label="成绩" align="center">
          <template #default="{ row }">
            <template v-if="isRunningProject(row.sportItem)">
              {{ formatRunningTime(row.storageValue) }}
            </template>
            <template v-else>
              {{ row.storageValue }} {{ row.sportItem?.unit }}
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="isPass" label="是否合格" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isPass === 1 ? 'success' : 'danger'" effect="dark" size="small">
              {{ row.isPass === 1 ? '合格' : '不合格' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="标准" align="center">
          <template #default="{ row }">
            <template v-if="row.student?.gender === '男' && row.sportItem?.malePass">
              {{ getStandardText(row.sportItem, '男') }}
            </template>
            <template v-else-if="row.student?.gender === '女' && row.sportItem?.femalePass">
              {{ getStandardText(row.sportItem, '女') }}
            </template>
            <template v-else>-</template>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" text @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" text @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="filteredScores.length" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 添加/编辑成绩对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑成绩' : '添加成绩'" width="500px" destroy-on-close @closed="resetForm">
      <el-form ref="scoreFormRef" :model="scoreForm" :rules="scoreRules" label-width="100px">
        <el-form-item label="学生" prop="stuId">
          <el-select v-model="scoreForm.stuId" filterable placeholder="选择学生" style="width: 100%" @change="handleStudentChange">
            <el-option v-for="student in students" :key="student.stuId" :label="`${student.stuId} - ${student.name}`" :value="student.stuId" />
          </el-select>
        </el-form-item>
        <el-form-item label="体测项目" prop="itemId">
          <el-select v-model="scoreForm.itemId" filterable placeholder="选择项目" style="width: 100%" @change="handleItemChange">
            <el-option v-for="item in filteredSportItems" :key="item.id" :label="item.itemName" :value="item.id" />
          </el-select>
        </el-form-item>

        <!-- 根据项目类型显示不同的成绩输入方式 -->
        <template v-if="currentItem">
          <!-- 跑步类项目（单位为秒） -->
          <el-form-item v-if="isRunningItem" label="成绩" prop="storageValue" required>
            <div class="time-input-container">
              <el-input-number v-model="timeMinutes" :min="0" :max="59" controls-position="right" placeholder="分钟" class="time-input" @change="updateStorageValue" />
              <span class="time-separator">:</span>
              <el-input-number v-model="timeSeconds" :min="0" :max="59" :precision="1" :step="0.1" controls-position="right" placeholder="秒" class="time-input" @change="updateStorageValue" />
              <span class="unit-text ml-10">分:秒</span>
            </div>
            <div class="form-hint">例如：3分30秒 = 3:30</div>
          </el-form-item>

          <!-- 非跑步类项目 -->
          <el-form-item v-else label="成绩" prop="storageValue" required>
            <div class="normal-input-container">
              <el-input-number v-model="scoreForm.storageValue" :precision="getInputPrecision()" :step="getInputStep()" :min="0" controls-position="right" style="width: 220px" />
              <span class="unit-text ml-10">{{ currentItem.unit }}</span>
            </div>
            <div v-if="currentItem.genderScope !== '通用'" class="form-hint">
              {{ getStandardHint() }}
            </div>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAllScores,
  addScore,
  updateScore,
  deleteScore
} from '@/api/score'
import { getSportItems } from '@/api/sportItem'
import { getStudentList } from '@/api/student'

// 状态变量
const loading = ref(false)
const scores = ref([])
const sportItems = ref([])
const students = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const searchText = ref('')
const itemFilter = ref('')
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const scoreFormRef = ref(null)

// 新增的状态变量
const currentItem = ref(null)
const timeMinutes = ref(0)
const timeSeconds = ref(0)

// 表单数据
const scoreForm = ref({
  id: null,
  stuId: '',
  itemId: null,
  storageValue: null
})

// 表单校验规则
const scoreRules = {
  stuId: [
    { required: true, message: '请选择学生', trigger: 'change' }
  ],
  itemId: [
    { required: true, message: '请选择体测项目', trigger: 'change' }
  ],
  storageValue: [
    { required: true, message: '请输入成绩数值', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (isRunningItem.value) {
          // 跑步项目，验证通过分钟和秒数输入
          if (timeMinutes.value === 0 && timeSeconds.value === 0) {
            callback(new Error('请输入有效的成绩时间'))
          } else {
            callback()
          }
        } else if (value === null || value === undefined) {
          callback(new Error('请输入成绩数值'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 计算属性
const filteredScores = computed(() => {
  let result = scores.value;

  if (searchText.value || itemFilter.value) {
    result = scores.value.filter(score => {
      const matchSearch = !searchText.value ||
        (score.student && (score.student.name.includes(searchText.value) ||
          score.student.stuId.includes(searchText.value)))

      const matchItem = !itemFilter.value || score.itemId === itemFilter.value

      return matchSearch && matchItem
    })
  }

  // 按学号排序
  return result.sort((a, b) => {
    if (a.student && b.student) {
      return a.student.stuId.localeCompare(b.student.stuId)
    }
    return 0
  })
})

const paginatedScores = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredScores.value.slice(start, end)
})

const isRunningItem = computed(() => {
  return currentItem.value &&
    (currentItem.value.unit === '秒') &&
    (currentItem.value.itemName.includes('米跑') || currentItem.value.itemName.includes('跑步'))
})

const currentStudent = computed(() => {
  if (!scoreForm.value.stuId) return null
  return students.value.find(student => student.stuId === scoreForm.value.stuId)
})

const filteredSportItems = computed(() => {
  if (!currentStudent.value) return sportItems.value

  const studentGender = currentStudent.value.gender

  return sportItems.value.filter(item => {
    // 通用项目对所有性别都显示
    if (item.genderScope === '通用') return true
    // 性别特定项目只对应性别显示
    return item.genderScope === studentGender
  })
})

// 生命周期方法
onMounted(async () => {
  loading.value = true
  try {
    await fetchScores()
    await fetchSportItems()
    await fetchStudents()
  } catch (error) {
    ElMessage.error('加载数据失败，请刷新重试')
  } finally {
    loading.value = false
  }
})

// 方法
async function fetchScores() {
  try {
    const res = await getAllScores()
    if (res.code === 200) {
      scores.value = res.data || []
    } else {
      ElMessage.error(res.message || '获取成绩列表失败')
    }
  } catch (error) {
    ElMessage.error('获取成绩列表失败')
  }
}

async function fetchSportItems() {
  try {
    const res = await getSportItems()
    if (res.code === 200) {
      sportItems.value = res.data || []
    }
  } catch (error) {
  }
}

async function fetchStudents() {
  try {
    const res = await getStudentList()
    if (res.code === 200) {
      students.value = res.data || []
    }
  } catch (error) {
  }
}

function handleSearch() {
  currentPage.value = 1
}

function handleSizeChange(size) {
  pageSize.value = size
  currentPage.value = 1
}

function handleCurrentChange(page) {
  currentPage.value = page
}

function getUnitText() {
  if (!scoreForm.value.itemId) return ''

  const item = sportItems.value.find(item => item.id === scoreForm.value.itemId)
  return item ? item.unit : ''
}

function getStandardText(sportItem, gender) {
  if (!sportItem) return '-'

  const isRunningItem = sportItem.unit === '秒'
  let standardValue = null

  if (gender === '男' && sportItem.malePass) {
    standardValue = sportItem.malePass
  } else if (gender === '女' && sportItem.femalePass) {
    standardValue = sportItem.femalePass
  }

  if (!standardValue) return '-'

  if (isRunningItem) {
    if (standardValue < 60) {
      return `≤ ${standardValue.toFixed(1)}秒`
    } else {
      const mins = Math.floor(standardValue / 60)
      const secs = Math.floor(standardValue % 60)
      const decimalPart = standardValue % 1 ? (standardValue % 1).toFixed(1).substring(1) : ''
      return `≤ ${mins}分${secs.toString().padStart(2, '0')}${decimalPart}秒`
    }
  } else {
    return `≥ ${standardValue} ${sportItem.unit}`
  }
}

function handleAdd() {
  isEdit.value = false
  scoreForm.value = {
    id: null,
    stuId: '',
    itemId: null,
    storageValue: null
  }
  currentItem.value = null
  timeMinutes.value = 0
  timeSeconds.value = 0
  dialogVisible.value = true

  // 确保表单重置
  setTimeout(() => {
    scoreFormRef.value?.clearValidate()
  }, 0)
}

function handleEdit(row) {
  isEdit.value = true
  scoreForm.value = {
    id: row.id,
    stuId: row.stuId,
    itemId: row.itemId,
    storageValue: row.storageValue
  }

  // 设置当前项目
  currentItem.value = sportItems.value.find(item => item.id === row.itemId)

  // 如果是跑步项目，转换时间格式
  if (isRunningItem.value && row.storageValue !== null) {
    convertSecondsToMinutesSeconds(row.storageValue)
  }

  dialogVisible.value = true

  // 确保表单重置
  setTimeout(() => {
    scoreFormRef.value?.clearValidate()
  }, 0)
}

function handleDelete(row) {
  if (!row || !row.id) {
    ElMessage.error('删除失败: 无效的成绩记录')
    return
  }

  ElMessageBox.confirm(
    `确定要删除 ${row.student?.name || ''} 的 ${row.sportItem?.itemName || ''} 成绩记录吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      console.log('删除成绩ID:', row.id)
      const res = await deleteScore(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchScores()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      // 提供更详细的错误提示
      console.error('删除失败:', error)
      if (error.response) {
        ElMessage.error(`删除失败: ${error.response.status} - ${error.response.data?.message || '服务器错误'}`)
      } else if (error.message) {
        ElMessage.error(`删除失败: ${error.message}`)
      } else {
        ElMessage.error('删除失败，请稍后重试')
      }
    }
  }).catch(() => {
    // 用户取消删除
  })
}

async function submitForm() {
  if (!scoreFormRef.value) return

  await scoreFormRef.value.validate(async valid => {
    if (valid) {
      // 检查是否有重复的成绩
      if (checkDuplicateScore()) {
        return; // 如果重复，不继续提交
      }

      submitting.value = true
      try {
        let res
        const formData = { ...scoreForm.value }

        // 确保跑步项目的数据正确
        if (isRunningItem.value) {
          formData.storageValue = timeMinutes.value * 60 + timeSeconds.value
        }

        // 确保itemId和stuId非空
        if (!formData.itemId) {
          throw new Error('请选择体测项目')
        }
        if (!formData.stuId) {
          throw new Error('请选择学生')
        }

        console.log('提交数据:', formData)

        if (isEdit.value) {
          // 更新成绩时需要ID
          if (!formData.id) {
            throw new Error('成绩ID不能为空')
          }
          res = await updateScore(formData)
        } else {
          // 添加成绩时去除id字段
          if (formData.id) {
            delete formData.id
          }
          res = await addScore(formData)
        }

        if (res.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
          dialogVisible.value = false
          await fetchScores()
        } else {
          ElMessage.error(res.message || '操作失败')
        }
      } catch (error) {
        // 提供更详细的错误信息
        console.error('提交失败:', error)
        if (error.response) {
          const status = error.response.status
          const message = error.response.data?.message
          ElMessage.error(`操作失败 (${status}): ${message || '服务器错误'}`)
        } else if (error.message) {
          ElMessage.error(`操作失败: ${error.message}`)
        } else {
          ElMessage.error('操作失败，请检查输入数据')
        }
      } finally {
        submitting.value = false
      }
    }
  })
}

// 新增一个函数来检查是否重复
function checkDuplicateScore() {
  if (!isEdit.value && scoreForm.value.stuId && scoreForm.value.itemId) {
    const existingScore = scores.value.find(
      score => score.stuId === scoreForm.value.stuId && score.itemId === scoreForm.value.itemId
    )

    if (existingScore) {
      ElMessage.warning(`该学生已有此项目成绩，请使用编辑功能修改`)
      return true
    }
  }
  return false
}

// 处理项目变化
function handleItemChange(itemId) {
  currentItem.value = sportItems.value.find(item => item.id === itemId)

  // 如果是跑步项目，初始化时间输入
  if (isRunningItem.value && scoreForm.value.storageValue !== null) {
    convertSecondsToMinutesSeconds(scoreForm.value.storageValue)
  } else {
    timeMinutes.value = 0
    timeSeconds.value = 0
  }

  // 检查是否重复
  checkDuplicateScore()
}

// 将秒数转换为分钟和秒
function convertSecondsToMinutesSeconds(totalSeconds) {
  if (totalSeconds === null || totalSeconds === undefined) {
    timeMinutes.value = 0
    timeSeconds.value = 0
    return
  }

  timeMinutes.value = Math.floor(totalSeconds / 60)
  timeSeconds.value = +(totalSeconds % 60).toFixed(1)
}

// 更新存储值
function updateStorageValue() {
  scoreForm.value.storageValue = timeMinutes.value * 60 + timeSeconds.value
}

// 获取输入精度
function getInputPrecision() {
  if (!currentItem.value) return 1

  const unit = currentItem.value.unit
  if (unit === 'cm' || unit === 'kg') return 1
  if (unit === 'ml') return 0
  return 1 // 默认精度
}

// 获取输入步长
function getInputStep() {
  if (!currentItem.value) return 1

  const unit = currentItem.value.unit
  if (unit === 'cm') return 0.5
  if (unit === 'kg') return 0.5
  if (unit === 'ml') return 100
  if (unit === '次' || unit === '次/分钟') return 1
  return 0.1 // 默认步长
}

// 获取标准提示
function getStandardHint() {
  if (!currentItem.value) return ''

  let standardValue
  if (currentItem.value.genderScope === '男') {
    standardValue = currentItem.value.malePass
  } else if (currentItem.value.genderScope === '女') {
    standardValue = currentItem.value.femalePass
  }

  if (standardValue === null || standardValue === undefined) return ''

  const unit = currentItem.value.unit
  const isRunning = unit === '秒'

  if (isRunning) {
    // 使用与列表相同的格式化逻辑
    if (standardValue < 60) {
      return `达标标准：≤ ${standardValue.toFixed(1)}秒`
    } else {
      const mins = Math.floor(standardValue / 60)
      const secs = Math.floor(standardValue % 60)
      const decimalPart = standardValue % 1 ? (standardValue % 1).toFixed(1).substring(1) : ''
      return `达标标准：≤ ${mins}分${secs.toString().padStart(2, '0')}${decimalPart}秒`
    }
  } else {
    return `达标标准：≥ ${standardValue} ${unit}`
  }
}

function resetForm() {
  // 重置表单数据
  scoreForm.value = {
    id: null,
    stuId: '',
    itemId: null,
    storageValue: null
  }

  // 重置关联数据
  currentItem.value = null
  timeMinutes.value = 0
  timeSeconds.value = 0

  // 清除验证状态
  if (scoreFormRef.value) {
    scoreFormRef.value.clearValidate()
    scoreFormRef.value.resetFields()
  }
}

function isRunningProject(sportItem) {
  return sportItem &&
    sportItem.unit === '秒' &&
    (sportItem.itemName.includes('米跑') || sportItem.itemName.includes('跑步'))
}

function formatRunningTime(totalSeconds) {
  if (totalSeconds === null || totalSeconds === undefined) return '-'

  // 特殊处理短跑项目（如50米跑），直接显示秒数
  if (totalSeconds < 60) {
    return `${totalSeconds.toFixed(1)}秒`
  }

  // 长跑项目（如1000米跑、800米跑）显示为分:秒格式
  const minutes = Math.floor(totalSeconds / 60)
  const seconds = Math.floor(totalSeconds % 60)
  const decimalPart = totalSeconds % 1 ? (totalSeconds % 1).toFixed(1).substring(1) : ''

  return `${minutes}分${seconds.toString().padStart(2, '0')}${decimalPart}秒`
}

// 处理学生变化
function handleStudentChange(stuId) {
  // 当学生改变时，如果已选的项目不适用于该学生的性别，则清空项目选择
  if (scoreForm.value.itemId) {
    const selectedItem = sportItems.value.find(item => item.id === scoreForm.value.itemId)
    const student = students.value.find(student => student.stuId === stuId)

    if (student && selectedItem && selectedItem.genderScope !== '通用' && selectedItem.genderScope !== student.gender) {
      scoreForm.value.itemId = null
      currentItem.value = null
    }
  }

  // 检查是否重复
  checkDuplicateScore()
}
</script>

<style scoped>
.scores-container {
  padding: 20px;
}

.scores-card {
  min-height: calc(100vh - 120px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

.time-input-container {
  display: flex;
  align-items: center;
}

.time-input {
  width: 100px;
}

.time-separator {
  margin: 0 8px;
  font-size: 16px;
  font-weight: bold;
}

.unit-text {
  margin-left: 10px;
  color: #606266;
}

.ml-10 {
  margin-left: 10px;
}

.form-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.normal-input-container {
  display: flex;
  align-items: center;
}
</style>